package com.vincce.sport.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.ConvertUtil;
import com.vincce.sport.core.utils.MapUtil;
import com.vincce.sport.entity.CompetitionGroup;
import com.vincce.sport.entity.CompetitionTeam;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.Player;
import com.vincce.sport.entity.PlayerDate;
import com.vincce.sport.entity.PreliminaryContest;
import com.vincce.sport.entity.Team;
import com.vincce.sport.entity.TeamDate;
import com.vincce.sport.mapper.CompetitionGroupMapper;
import com.vincce.sport.mapper.CompetitionTeamMapper;
import com.vincce.sport.mapper.PlayerDateMapper;
import com.vincce.sport.mapper.PlayerMapper;
import com.vincce.sport.mapper.PreliminaryContestMapper;
import com.vincce.sport.mapper.TeamDateMapper;
import com.vincce.sport.mapper.TeamMapper;

@Controller
@RequestMapping("/scoreManage")
public class ScoreManageController extends BaseController{

	@Resource
	private PreliminaryContestMapper preliminaryContestMapper;
	
	@Resource
	private TeamDateMapper teamDateMapper;
	
	@Resource
	private PlayerMapper playerMapper;
	
	@Resource
	private PlayerDateMapper playerDateMapper;
	
	@Resource
	private CompetitionGroupMapper competitionGroupMapper;
	
	@Resource
	private TeamMapper teamMapper;
	
	@Resource
	private CompetitionTeamMapper competitionTeamMapper;
	
	@RequestMapping("/list")
	public String list(HttpServletRequest request, Model model, PreliminaryContest preliminaryContest,Page<PreliminaryContest> page) throws ParseException{
		String date = request.getParameter("date");
		if(date != null && !date.equals("")){
			preliminaryContest.setDate(date);
		}
		Map<String, Object> filter= MapUtil.ConvertObjToMap(preliminaryContest);
		page.setFilter(filter);
		page.setResult(preliminaryContestMapper.queryPreliminaryContest(page));
		Long totalCount = preliminaryContestMapper.queryPreliminaryContestCount(page);
		page.setTotal(totalCount==0?1:totalCount);
        model.addAttribute("page",page);
        model.addAttribute("preliminaryContest", preliminaryContest);
		return "/backstage/scoreManage";
	}
	
	@RequestMapping("/toUpdatePage")
	public String toUpdatePage(Model model, Long id,String teamIds){
		PreliminaryContest preliminaryContest = preliminaryContestMapper.findPreliminaryContestById(id);
		/*String[] teamIdArra = teamIds.split(",");
		Integer teamId = Integer.valueOf(teamIdArra[0]);
		Integer teamTwoId = Integer.valueOf(teamIdArra[1]);*/
		Integer teamId = preliminaryContest.getTeamId().intValue();
		Integer teamTwoId = preliminaryContest.getTeamIdTwo().intValue();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contestId", id);
		param.put("teamId", teamId);
		List<TeamDate> teamDateList = teamDateMapper.queryTeamDateByContest(param);
		List<Player> playerList = playerMapper.queryPlayerByTeamId(param);
		for(Player player : playerList){
			param.clear();
			param.put("contestId", id);
			param.put("playerId", player.getId());
			PlayerDate playerDate = playerDateMapper.queryPlayerDateByPlayerId(param);
			player.setPlayerDate(playerDate);
		}
		TeamDate teamDate = new TeamDate();
		if (teamDateList != null && !teamDateList.isEmpty()) {
			teamDate = teamDateList.get(0);
		}else{
			Team team = teamMapper.queryTeamById(teamId);
			teamDate.setTeamId(teamId);
			teamDate.setTeamName(team.getName());
		}
		param.put("teamId", teamTwoId);
		List<TeamDate> teamDateList2 = teamDateMapper.queryTeamDateByContest(param);
		List<Player> playerList2 = playerMapper.queryPlayerByTeamId(param);
		for(Player player : playerList2){
			param.clear();
			param.put("contestId", id);
			param.put("playerId", player.getId());
			PlayerDate playerDate = playerDateMapper.queryPlayerDateByPlayerId(param);
			player.setPlayerDate(playerDate);
		}
		TeamDate teamDate2 = new TeamDate();
		if (teamDateList2 != null && !teamDateList2.isEmpty()) {
			teamDate2 = teamDateList2.get(0);
		}else{
			Team team = teamMapper.queryTeamById(teamTwoId);
			teamDate2.setTeamId(teamTwoId);
			teamDate2.setTeamName(team.getName());
		}
		
		model.addAttribute("preliminaryContest", preliminaryContest);
		model.addAttribute("teamDate", teamDate);
		model.addAttribute("teamTwoDate", teamDate2);
		model.addAttribute("playerList", playerList);
		model.addAttribute("playerTwoList", playerList2);
		model.addAttribute("contestId", id);
		return "/backstage/scoreUpdatePage";
	}
	
	/**
	 * 球队总分数据
	 * @param request
	 * @param teamDate
	 * @return
	 */
	@RequestMapping("/totalScoreAddOrUpdate")
	@ResponseBody
	public String totalScoreAddOrUpdate(HttpServletRequest request){
		Long userId = getCurrentUser().getId();
		Long contestId = Long.valueOf(request.getParameter("contestId"));
		Integer seasonId = Integer.valueOf(request.getParameter("seasonId"));
		Integer type = Integer.valueOf(request.getParameter("type"));
		
		Integer teamId = Integer.valueOf(request.getParameter("teamId"));
		Integer teamFirstSectionScore = Integer.valueOf(request.getParameter("teamFirstSectionScore"));
		Integer teamSecondSectionScore = Integer.valueOf(request.getParameter("teamSecondSectionScore"));
		Integer teamThirdSectionScore = Integer.valueOf(request.getParameter("teamThirdSectionScore"));
		Integer teamFourthSectionScore = Integer.valueOf(request.getParameter("teamFourthSectionScore"));
		Integer teamTotalScore = Integer.valueOf(request.getParameter("teamTotalScore"));
		
		Integer teamTwoId = Integer.valueOf(request.getParameter("teamTwoId"));
		Integer teamTwoFirstSectionScore = Integer.valueOf(request.getParameter("teamTwoFirstSectionScore"));
		Integer teamTwoSecondSectionScore = Integer.valueOf(request.getParameter("teamTwoSecondSectionScore"));
		Integer teamTwoThirdSectionScore = Integer.valueOf(request.getParameter("teamTwoThirdSectionScore"));
		Integer teamTwoFourthSectionScore = Integer.valueOf(request.getParameter("teamTwoFourthSectionScore"));
		Integer teamTwoTotalScore = Integer.valueOf(request.getParameter("teamTwoTotalScore"));
		
		TeamDate teamDate = new TeamDate();
		teamDate.setSeasonId(seasonId);
		teamDate.setContestId(contestId);
		teamDate.setTeamId(teamId);
		teamDate.setFirstSectionScore(teamFirstSectionScore);
		teamDate.setSecondSectionScore(teamSecondSectionScore);
		teamDate.setThirdSectionScore(teamThirdSectionScore);
		teamDate.setFourthSectionScore(teamFourthSectionScore);
		if(!CheckUtil.isEmpty(request.getParameter("teamOvertimeOneScore"))){
			Integer teamOvertimeOneScore = Integer.valueOf(request.getParameter("teamOvertimeOneScore"));
			teamDate.setOvertimeOneScore(teamOvertimeOneScore);
		}
		if(!CheckUtil.isEmpty(request.getParameter("teamOvertimeTwoScore"))){
			Integer teamOvertimeTwoScore = Integer.valueOf(request.getParameter("teamOvertimeTwoScore"));
			teamDate.setOvertimeTwoScore(teamOvertimeTwoScore);
		}
		if(!CheckUtil.isEmpty(request.getParameter("teamOvertimeThreeScore"))){
			Integer teamOvertimeThreeScore = Integer.valueOf(request.getParameter("teamOvertimeThreeScore"));
			teamDate.setOvertimeThreeScore(teamOvertimeThreeScore);
		}
		if(!CheckUtil.isEmpty(request.getParameter("teamOvertimeFourScore"))){
			Integer teamOvertimeFourScore = Integer.valueOf(request.getParameter("teamOvertimeFourScore"));
			teamDate.setOvertimeFourScore(teamOvertimeFourScore);
		}
		teamDate.setTotalScore(teamTotalScore);
		teamDate.setTotalLossScore(teamTwoTotalScore);
		teamDate.setCompetitor(teamTwoId);
		if(teamTotalScore > teamTwoTotalScore){
			teamDate.setWin(1);
		}else{
			teamDate.setWin(2);
		}
		Long count = insertOrUpdateTeamDate(teamDate,userId);
		
		TeamDate teamDate2 = new TeamDate();
		teamDate2.setSeasonId(seasonId);
		teamDate2.setContestId(contestId);
		teamDate2.setTeamId(teamTwoId);
		teamDate2.setFirstSectionScore(teamTwoFirstSectionScore);
		teamDate2.setSecondSectionScore(teamTwoSecondSectionScore);
		teamDate2.setThirdSectionScore(teamTwoThirdSectionScore);
		teamDate2.setFourthSectionScore(teamTwoFourthSectionScore);
		if(!CheckUtil.isEmpty(request.getParameter("teamTwoOvertimeOneScore"))){
			Integer teamTwoOvertimeOneScore = Integer.valueOf(request.getParameter("teamTwoOvertimeOneScore"));
			teamDate2.setOvertimeOneScore(teamTwoOvertimeOneScore);
		}
		if(!CheckUtil.isEmpty(request.getParameter("teamTwoOvertimeTwoScore"))){
			Integer teamTwoOvertimeTwoScore = Integer.valueOf(request.getParameter("teamTwoOvertimeTwoScore"));
			teamDate2.setOvertimeTwoScore(teamTwoOvertimeTwoScore);
		}
		if(!CheckUtil.isEmpty(request.getParameter("teamTwoOvertimeThreeScore"))){
			Integer teamTwoOvertimeThreeScore = Integer.valueOf(request.getParameter("teamTwoOvertimeThreeScore"));
			teamDate2.setOvertimeThreeScore(teamTwoOvertimeThreeScore);
		}
		if(!CheckUtil.isEmpty(request.getParameter("teamTwoOvertimeFourScore"))){
			Integer teamTwoOvertimeFourScore = Integer.valueOf(request.getParameter("teamTwoOvertimeFourScore"));
			teamDate2.setOvertimeFourScore(teamTwoOvertimeFourScore);
		}
		teamDate2.setTotalScore(teamTwoTotalScore);
		teamDate2.setTotalLossScore(teamTotalScore);
		teamDate2.setCompetitor(teamId);
		if(teamTwoTotalScore > teamTotalScore){
			teamDate2.setWin(1);
		}else{
			teamDate2.setWin(2);
		}
		count = insertOrUpdateTeamDate(teamDate2, userId);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("seasonId", seasonId);
		map.put("teamId", teamId);
		List<CompetitionTeam> competitionTeamList = competitionTeamMapper.findCompetitionTeamList(map);
		CompetitionTeam competitionTeam = null;
		if(!CheckUtil.isEmpty(competitionTeamList)){
			competitionTeam = competitionTeamList.get(0);
		}
		if(type == 1){		//预赛赛程
			groupTeamRanking(competitionTeam.getGroupId());
		}
		return JSON.toJSONString(count > 0);
	}
	
	@RequestMapping("/groupRanking")
	@ResponseBody
	public String groupRanking(HttpServletRequest request, Long groupId){
		Long count = 0L;
		List<CompetitionTeam> competitionTeamList = competitionTeamMapper.queryGroupTeamScore(groupId);
		Map<String, Object> result = new HashMap<String, Object>();
		if(competitionTeamList == null || competitionTeamList.isEmpty()){
			result.put("message", "该小组不存在或小组暂无参数球队或小组无任何已结束的比赛,暂时无法排序");
			result.put("flag", false);
			return JSON.toJSONString(result);
		}
		List<CompetitionTeam> maxList = new ArrayList<CompetitionTeam>();		//积分最大的
		maxList.add(competitionTeamList.get(0));
		CompetitionTeam maxTeam = maxList.get(0);
		for(int i = 1; i < competitionTeamList.size(); i++){
			CompetitionTeam competitionTeam = competitionTeamList.get(i);
			if(competitionTeam.getIntegration() > maxTeam.getIntegration()){
				maxList.clear();
				maxList.add(competitionTeam);
				maxTeam = competitionTeam;
			}else if(competitionTeam.getIntegration() == maxTeam.getIntegration()){
				maxList.add(competitionTeam);
			}
		}
		if(maxList.size() > 1){			//存在多个积分相同的
			boolean flag = false;
			if(maxList.size() == 2){	//两个队伍存在积分相同情况,根据胜负规则判断
				CompetitionGroup competitionGroup = competitionGroupMapper.findCompetitionGroupById(maxList.get(0).getGroupId());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("teamId", maxList.get(0).getTeamId());
				map.put("seasonId", competitionGroup.getSeasonId());
				map.put("competitor", maxList.get(1).getTeamId());
				map.put("winOrLose", "win");
				long teamWinCount1 = teamDateMapper.queryTeamDateByCount(map);		//第一个球队胜第二个球队的场次
				map.clear();
				map.put("teamId", maxList.get(1).getTeamId());
				map.put("seasonId", competitionGroup.getSeasonId());
				map.put("competitor", maxList.get(0).getTeamId());
				map.put("winOrLose", "win");
				long teamWinCount2 = teamDateMapper.queryTeamDateByCount(map);		//第一个球队胜第二个球队的场次
				if(teamWinCount1 > teamWinCount2){		//球队1胜场大于球队2
					CompetitionTeam competitionTeam = maxList.get(0);
					competitionTeam.setType(1);
					count = competitionTeamMapper.updateType(groupId);		//重置小组排名
					count = competitionTeamMapper.update(competitionTeam);
					flag = true;
				}else if(teamWinCount1 < teamWinCount2){	//球队2胜场大于球队1
					CompetitionTeam competitionTeam = maxList.get(1);
					competitionTeam.setType(1);
					count = competitionTeamMapper.updateType(groupId);		//重置小组排名
					count = competitionTeamMapper.update(competitionTeam);
					flag = true;
				}
			}
			if(!flag){
				StringBuffer buffer = new StringBuffer();
				for(int i = 0; i < maxList.size(); i++){
					buffer.append(maxList.get(i).getTeamId()+",");
				}
				String teamIds = buffer.toString();
				teamIds = teamIds.substring(0, teamIds.length()-1);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("groupId", groupId);
				map.put("teamIds", teamIds);
				TeamDate teamDate = teamDateMapper.queryScoreRate(map);
				for(CompetitionTeam competitionTeam : maxList){
					if(competitionTeam.getTeamId() == Long.valueOf(teamDate.getTeamId())){
						competitionTeam.setType(1);
						count = competitionTeamMapper.updateType(groupId);		//重置小组排名
						count = competitionTeamMapper.update(competitionTeam);
					}
				}
			}
		}else{
			CompetitionTeam competitionTeam = maxList.get(0);
			competitionTeam.setType(1);
			count = competitionTeamMapper.updateType(groupId);		//重置小组排名
			count = competitionTeamMapper.update(competitionTeam);
		}
		if(count > 0){
			result.put("message", "操作成功");
			result.put("flag", true);
		}else{
			result.put("message", "操作失败");
			result.put("flag", true);
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 小组球队排名
	 * @param groupId
	 * @return
	 */
	private void groupTeamRanking(Long groupId){
		List<CompetitionTeam> competitionTeamList = competitionTeamMapper.queryGroupTeamScore(groupId);
		List<CompetitionTeam> maxList = new ArrayList<CompetitionTeam>();		//积分最大的
		maxList.add(competitionTeamList.get(0));
		CompetitionTeam maxTeam = maxList.get(0);
		for(int i = 1; i < competitionTeamList.size(); i++){
			CompetitionTeam competitionTeam = competitionTeamList.get(i);
			if(competitionTeam.getIntegration() > maxTeam.getIntegration()){
				maxList.clear();
				maxList.add(competitionTeam);
				maxTeam = competitionTeam;
			}else if(competitionTeam.getIntegration() == maxTeam.getIntegration()){
				maxList.add(competitionTeam);
			}
		}
		if(maxList.size() > 1){			//存在多个积分相同的
			/*if(maxList.size() == 2){	//两个队伍存在积分相同情况,计算两队得失分率
				
			}else if(maxList.size() == 3){			//三个队伍存在积分相同情况(算小分)
				
			}*/
			boolean flag = false;
			if(maxList.size() == 2){	//两个队伍存在积分相同情况,根据胜负规则判断
				CompetitionGroup competitionGroup = competitionGroupMapper.findCompetitionGroupById(maxList.get(0).getGroupId());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("teamId", maxList.get(0).getTeamId());
				map.put("seasonId", competitionGroup.getSeasonId());
				map.put("competitor", maxList.get(1).getTeamId());
				map.put("winOrLose", "win");
				long teamWinCount1 = teamDateMapper.queryTeamDateByCount(map);		//第一个球队胜第二个球队的场次
				map.clear();
				map.put("teamId", maxList.get(1).getTeamId());
				map.put("seasonId", competitionGroup.getSeasonId());
				map.put("competitor", maxList.get(0).getTeamId());
				map.put("winOrLose", "win");
				long teamWinCount2 = teamDateMapper.queryTeamDateByCount(map);		//第一个球队胜第二个球队的场次
				if(teamWinCount1 > teamWinCount2){		//球队1胜场大于球队2
					CompetitionTeam competitionTeam = maxList.get(0);
					competitionTeam.setType(1);
					competitionTeamMapper.updateType(groupId);		//重置小组排名
					competitionTeamMapper.update(competitionTeam);
					flag = true;
				}else if(teamWinCount1 < teamWinCount2){	//球队2胜场大于球队1
					CompetitionTeam competitionTeam = maxList.get(1);
					competitionTeam.setType(1);
					competitionTeamMapper.updateType(groupId);		//重置小组排名
					competitionTeamMapper.update(competitionTeam);
					flag = true;
				}
			}
			if(!flag){
				StringBuffer buffer = new StringBuffer();
				for(int i = 0; i < maxList.size(); i++){
					buffer.append(maxList.get(i).getTeamId()+",");
				}
				String teamIds = buffer.toString();
				teamIds = teamIds.substring(0, teamIds.length()-1);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("groupId", groupId);
				map.put("teamIds", teamIds);
				TeamDate teamDate = teamDateMapper.queryScoreRate(map);
				for(CompetitionTeam competitionTeam : maxList){
					if(competitionTeam.getTeamId() == Long.valueOf(teamDate.getTeamId())){
						competitionTeam.setType(1);
						competitionTeamMapper.updateType(groupId);		//重置小组排名
						competitionTeamMapper.update(competitionTeam);
					}
				}
			}
		}else{
			CompetitionTeam competitionTeam = maxList.get(0);
			competitionTeam.setType(1);
			competitionTeamMapper.updateType(groupId);		//重置小组排名
			competitionTeamMapper.update(competitionTeam);
		}
	}
	
	private Long insertOrUpdateTeamDate(TeamDate teamDate,Long userId){
		Long count = 0L;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contestId", teamDate.getContestId());
		param.put("teamId", teamDate.getTeamId());
		List<TeamDate> teamDateList = teamDateMapper.queryTeamDateByContest(param);
		if(CheckUtil.isEmpty(teamDateList)){
			teamDate.setCreateTime(new Date());
			teamDate.setCreateUser(userId.intValue());
			count = teamDateMapper.insertTeamDate(teamDate);
		}else{
			Integer teamDateId = teamDateList.get(0).getId();
			teamDate.setId(teamDateId);
			teamDate.setUpdateTime(new Date());
			teamDate.setUpdateUser(userId.intValue());
			count = teamDateMapper.updateTeamDate(teamDate);
		}
		return count;
	}
	
	@RequestMapping("/teamDateAddOrUpdate")
	@ResponseBody
	public String teamDateAddOrUpdate(HttpServletRequest request, TeamDate teamDate){
		Long userId = getCurrentUser().getId();
		float freeThrowHitRate = ConvertUtil.percentNum(teamDate.getFreeThrowHitTotal(), teamDate.getFreeThrowTotal());
		float threePointsHitRate = ConvertUtil.percentNum(teamDate.getThreePointsHitTotal(), teamDate.getThreePointsTotal());
		float twoPointsHitRate = ConvertUtil.percentNum(teamDate.getTwoPointsHitTotal(), teamDate.getTwoPointsTotal());
		float shootBasketHitRate = ConvertUtil.percentNum(teamDate.getShootBasketHitTotal(), teamDate.getShootBasketTotal());
		teamDate.setFreeThrowHitRate(freeThrowHitRate);
		teamDate.setThreePointsHitRate(threePointsHitRate);
		teamDate.setTwoPointsHitRate(twoPointsHitRate);
		teamDate.setShootBasketHitRate(shootBasketHitRate);
		Long count = insertOrUpdateTeamDate(teamDate, userId);
		return JSON.toJSONString(count > 0);
	}
	
	@RequestMapping("/playerDateAddOrUpdate")
	@ResponseBody
	public String playerDateAddOrUpdate(HttpServletRequest request, PlayerDate playerDate){
		Long userId = getCurrentUser().getId();
		float freeThrowHitRate = ConvertUtil.percentNum(playerDate.getFreeThrowHitTotal(), playerDate.getFreeThrowTotal());
		float threePointsHitRate = ConvertUtil.percentNum(playerDate.getThreePointsHitTotal(), playerDate.getThreePointsTotal());
		float twoPointsHitRate = ConvertUtil.percentNum(playerDate.getTwoPointsHitTotal(), playerDate.getTwoPointsTotal());
		playerDate.setFreeThrowHitRate(freeThrowHitRate);
		playerDate.setThreePointsHitRate(threePointsHitRate);
		playerDate.setTwoPointsHitRate(twoPointsHitRate);
		
		Integer shootBasketTotal = playerDate.getTwoPointsTotal() + playerDate.getThreePointsTotal();
		Integer shootBasketHitTotal = playerDate.getTwoPointsHitTotal() + playerDate.getThreePointsHitTotal();
		playerDate.setShootBasketTotal(shootBasketTotal);
		playerDate.setShootBasketHitTotal(shootBasketHitTotal);
		Long count = 0L;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("contestId", playerDate.getContestId());
		param.put("playerId", playerDate.getPlayerId());
		//param.put("teamId", playerDate.getTeamId());
		List<PlayerDate> playerDateList = playerDateMapper.queryPlayerDateByContest(param);
		if(CheckUtil.isEmpty(playerDateList)){
			playerDate.setCreateTime(new Date());
			playerDate.setCreateUser(userId.intValue());
			count = playerDateMapper.insertPalyerDate(playerDate);
		}else{
			Integer playerDateId = playerDateList.get(0).getId();
			playerDate.setId(playerDateId);
			playerDate.setUpdateTime(new Date());
			playerDate.setUpdateUser(userId.intValue());
			count = playerDateMapper.updatePalyerDate(playerDate);
		}
		return JSON.toJSONString(count > 0);
	}
}
